package com.hns.tool.pub;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Service;

/**
 * 文件上传工具
 * @author:Fisher
 * @email:zhuangcaijin@126.com
 * @version Revision 2.0.0
 */
@Service
public class FileUploadUtil {
    
	/**
	 * 上传文件
	 * @param f 输入流
	 * @param fileName 文件名称
	 * @param uploadPath 上传路径
	 * @throws IOException
	 * @author:Fisher
	 * @email:zhuangcaijin@126.com
	 */
    public static void uploadFile(InputStream f, String fileName, String uploadPath) throws IOException {
        
        File upLoadFile = new File(uploadPath);
        if (!upLoadFile.exists()) {
            upLoadFile.mkdirs();
        }
        File file = new File(uploadPath, fileName);
        int bytesRead = 0;
        OutputStream os = new FileOutputStream(file);
        byte[] buffer = new byte[2048];
        while ((bytesRead = f.read(buffer, 0, 2048)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.flush();
        os.close();
    }
    
    /**
     * 保存内容到文件
     * @param f 输入流
     * @param fileName 文件名称
     * @param uploadPath 上传路径
     * @throws Exception
     * @throws FileNotFoundException
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    //TODO
    public static void saveWsdlFile(InputStream f, String fileName, String uploadPath) throws Exception, FileNotFoundException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = f.read()) != -1) {
            bytestream.write(ch);
        }
        byte[] wsdlArray = bytestream.toByteArray();
        bytestream.close();
        // 替换指定字符串
        String str = new String(wsdlArray, "UTF-8");
        if (str.indexOf("minOccurs=\"0\"") != -1) {
            str = str.replaceAll("minOccurs=\"0\"", "");
        }
        File upLoadFile = new File(uploadPath);
        if (!upLoadFile.exists()) {
            upLoadFile.mkdirs();
        }
        File file = new File(uploadPath, fileName);
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write(str);
        bw.flush();
        bw.close();
        System.out.println("写入文件成功。");
    }
    
    /**
     * 获取当前时间
     * @return 当前时间字符串
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public String getDateTime() {
        String datnow = "";
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        datnow = sdf.format(dt);
        return datnow;
    }
    
    /**
     * 复制文件到指定目录中
     * @param sourceFile 源文件目录
     * @param targetPath 指定目录
     * @param targetName 指定文件名
     * @throws IOException
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static void copyFile(String sourceFile, String targetPath, String targetName) throws IOException {
        copyFile(new File(sourceFile), targetPath, targetName);
    }
    
    /**
     * 复制文件到指定目录中
     * @param sourceFile 源文件
     * @param targetPath 指定目录
     * @param targetName 指定文件名
     * @throws IOException
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static void copyFile(File sourceFile, String targetPath, String targetName) throws IOException {
        if (sourceFile.exists()) {
            File targetFolder = new File(targetPath);
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();
            }
            File targetFile = new File(targetPath + "/" + targetName);
            copyFile(sourceFile, targetFile);
        }
    }
    
    /**
     * 复制文件内容到指定文件
     * @param sourceFile 源文件
     * @param targetFile 指定文件
     * @throws IOException
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        
        try {
            if (sourceFile.exists()) {
                if (!targetFile.exists()) {
                    targetFile.createNewFile();
                }
                inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
                outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
                byte[] b = new byte[1024 * 5];
                int len;
                while ((len = inBuff.read(b)) != -1) {
                    outBuff.write(b, 0, len);
                }
                outBuff.flush();
            }
            
        } finally {
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
    
    /**
     * 删除指定文件夹下所有文件
     * @param path 文件夹完整绝对路径
     * @return 是否已删除
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }
    
    /**
     * 删除文件夹
     * @param folderPath 文件夹完整绝对路径
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 删除文件
     * @param fullPath 文件完整绝对路径
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static void delFile(String fullPath) {
        File file = new File(fullPath);
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
                System.out.println("delete file: " + file.getAbsolutePath());
            }
            
            if (file.isDirectory()) {
                String[] tempList = file.list();
                for (int i = 0; i < tempList.length; i++) {
                    delFile(fullPath + "/" + tempList[i]);// 先删除文件夹里面的文件
                }
                file.delete(); // 删除空文件夹
                System.out.println("delete Directory: " + file.getAbsolutePath());
            }
        }
    }
    
    /**
     * 删除空文件夹
     * @param fullPath 文件夹路径
     * @return 是否已删除
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static boolean delFolderIfEmpty(String fullPath) {
        File file = new File(fullPath);
        if (file.exists() && file.isDirectory()) {
            String[] tempList = file.list();
            if (ArrayUtils.isEmpty(tempList)) {
                return file.delete();
            }
        }
        return false;
    }
    
    // 得到工程的根目录
    /**
     * 得到工程的根目录
     * @param request
     * @return 工程根目录字符串
     * @author:Fisher
	 * @email:zhuangcaijin@126.com
     */
    public static String getWebRoot(HttpServletRequest request) {
        String webRoot  =null;
        if (webRoot == null) {
            webRoot = request.getSession().getServletContext().getRealPath("/");
        }
        return webRoot;
    }
    
    public static void main(String args[]) {
        // RepExecuteUpload a = new RepExecuteUpload();
        // a.delFile("E:/SinoVANUploadfiles/wsdl/1.txt");
        
        File targetFolder = new File("E:/SinoVANUploadfiles/wsdl/1/2/txt");
        if (!targetFolder.exists()) {
            targetFolder.mkdirs();
        }
    }
    
}
